#Alexander F. Gazmararian
#afg2@princeton.edu

library(tidyverse)
library(modelsummary)

source("code/fun/savefig.r")
source("code/fun/book_theme.r")
source("code/fun/fix_txt.r")
source("code/fun/coefnames4tables.r")

#load data
g <- readRDS("data/NatCAPS_20220928.rds")

# Descriptive plot ----
ira.plot <-
  g %>%
  pivot_longer(cols = c(ira_rep,ira_dem,ira_ff,ira_re)) %>%
  mutate(
    name = case_when(
      name == "ira_rep" ~ "Republicans",
      name == "ira_dem" ~ "Democrats",
      name == "ira_ff" ~ "Fossil fuel companies",
      name == "ira_re" ~ "Renewable companies"
    )
  ) %>%
  mutate(
    name = factor(name, ordered = TRUE, levels = c(
      "Democrats", "Republicans", "Fossil fuel companies", "Renewable companies"
    ))
  ) %>%
  mutate(reverse = ifelse(value %in% c("Very likely to reverse","Somewhat likely to reverse"), 1, 0)) %>%
  ggplot(aes(x=name,y=reverse,weight=weights)) +
  stat_summary(fun.data = "mean_cl_normal", geom="errorbar",width=0) +
  stat_summary(fun.data = mean_cl_normal, geom="errorbar",fun.args=list(conf.int=.9),width=0,size=1.75) +
  stat_summary(fun = mean, geom="point",size=4) +
  coord_flip(ylim = c(0.1,.6)) +
  scale_y_continuous(labels = scales::percent, breaks = seq(.1, .6, .1)) +
  book_theme +
  labs(x="", y="Likely to try to reverse")
ira.plot
savefig(ira.plot, "3.7_figure_irareverse", height = 1.8, filepath = "figures/")

# Estimate linear models ----
ols.ira <- list()
ols.ira[["Democrats"]] <- lm(ira_dem_scale ~ age + Female + Black + Hispanic + CollegeDegree + PartySummary + rural, g, weight = weights)
ols.ira[["Republicans"]] <- lm(ira_rep_scale ~ age + Female + Black + Hispanic + CollegeDegree + PartySummary + rural, g, weight = weights)
ols.ira[["Independents"]] <- lm(ira_ind_scale ~ age + Female + Black + Hispanic + CollegeDegree + PartySummary + rural, g, weight = weights)
ols.ira[["FF Companies"]] <- lm(ira_ff_scale ~ age + Female + Black + Hispanic + CollegeDegree + PartySummary + rural, g, weight = weights)
ols.ira[["RE Companies"]] <- lm(ira_re_scale ~ age + Female + Black + Hispanic + CollegeDegree + PartySummary + rural, g, weight = weights)
#specify coefficients
file <- "tables/ch3/ols_irasupport.txt"
modelsummary(
  ols.ira,
  vcov = "HC2",
  stars = c("*"=.1,"**"=.05,"***"=.01),
  coef_map = coefnames,
  gof_map = c("nobs", "adj.r.squared"),
  escape=FALSE,
  output="latex") %>%
  cat(., file = file)
fix_txt(file)

